import os
import shutil


#
# def write_text_to_file(file_path, text, mode="w"):
#     file_path = os.path.join(project_root_path, file_path)
#     try:
#         # 创建父路径（如果不存在）
#         os.makedirs(os.path.dirname(file_path), exist_ok=True)
#         # 写入文件
#         with open(file_path, mode, encoding="utf-8") as file:
#             file.write(text)
#         print("文本已成功写入文件：", file_path)
#     except Exception as e:
#         print("写入文件时发生错误：", e)


#
# def rename_if_exists(directory, full_file_name):
#     path_obj = pathlib.Path(full_file_name)
#     if path_obj.is_absolute():
#         # 若传入绝对路径，仅保留文件名部分
#         file_name = path_obj.name
#         directory = pathlib.Path(directory)  # 将directory转换为Path对象
#     else:
#         # 若传入相对路径或仅文件名，结合传入的目录生成完整路径
#         file_name = full_file_name
#         directory = pathlib.Path(directory) / path_obj.parent
#
#     base_name, ext = os.path.splitext(file_name)
#     counter = 2
#
#     full_path_obj = directory / file_name
#     while os.path.exists(full_path_obj):
#         new_file_name = f"{base_name}_{counter}{ext}"
#         full_path_obj = directory / new_file_name
#         if os.path.exists(full_path_obj):
#             counter += 1
#         else:
#             break
#
#     # 若原文件名不存在，则无需做任何操作，直接返回原文件名或路径
#     if str(full_path_obj) == str(directory / file_name):
#         return str(directory / file_name)
#
#     # os.rename(str(directory / file_name), str(full_path_obj))
#     # print(f"Renamed '{str(directory / file_name)}' to '{str(full_path_obj)}'")
#     return str(full_path_obj)

# 使用示例
# directory = "/Users/duyi/PycharmProjects/waihui_track/out_print/tree_picture"
# file_or_path = "/Users/duyi/PycharmProjects/waihui_track/out_print/tree_picture/2022-02-16_南宫市宇帅服装服饰有限公司_100000.dot"  # 或者 "/path/to/your/directory/aaa.xlsx" 等
#
# new_file_name_or_path = rename_if_exists(directory, file_or_path)
# print(new_file_name_or_path)


def copy_files_with_names(folder1, folder2, name_list):
    # 遍历文件夹1下的所有文件
    for root, _, files in os.walk(folder1):
        for file in files:
            file_path = os.path.join(root, file)
            # 检查文件名是否包含在name_list中
            if any(name in file for name in name_list):
                # 构建文件在文件夹2中的路径
                dest_path = os.path.join(folder2, file)
                # 复制文件到文件夹2中
                shutil.copy2(file_path, dest_path)


def contains_any_character(file_path, character_list):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            for line in file:
                if any(character in line for character in character_list):
                    return True
        return False
    except Exception as e:
        print(f"Error reading file {file_path}: {e}")
        return False


def delete_all_files_in_folder(folder_path):
    """
    删除指定文件夹下的所有文件和子文件夹。

    :param folder_path: 文件夹的路径
    """
    # 检查文件夹是否存在
    if not os.path.exists(folder_path):
        print(f"文件夹 '{folder_path}' 不存在")
        return

    # 遍历文件夹中的所有文件和子文件夹
    for root, dirs, files in os.walk(folder_path):
        # 删除子文件夹中的所有文件
        for filename in files:
            file_path = os.path.join(root, filename)
            try:
                os.remove(file_path)
                print(f"文件 '{file_path}' 已删除")
            except Exception as e:
                print(f"删除文件 '{file_path}' 时出错: {e}")
        # 删除子文件夹
        for dir_name in dirs:
            dir_path = os.path.join(root, dir_name)
            try:
                shutil.rmtree(dir_path)
                print(f"文件夹 '{dir_path}' 已删除")
            except Exception as e:
                print(f"删除文件夹 '{dir_path}' 时出错: {e}")


def get_files_in_directory_only_one_layer(directory):
    """
    遍历指定目录的顶层，仅获取文件的路径，并返回一个列表。
    """
    file_list = []  # 初始化一个空列表来存储文件路径
    with os.scandir(directory) as entries:
        for entry in entries:
            if entry.is_file():  # 检查当前条目是否为文件
                if not entry.name.startswith("."):
                    file_list.append(entry.path)  # 如果是文件，则添加其路径到列表中
    return file_list  # 返回包含文件路径的列表


def write_string_to_file(file_path: str, content: str):
    try:
        with open(file_path, 'w') as file:
            file.write(content)
    except IOError as e:
        print(f"An error occurred while writing to the file: {e}")


def get_all_files(start_path):
    """返回指定目录及其子目录下的所有文件的完整路径列表。"""
    file_list = []
    for root, dirs, files in os.walk(start_path):
        for file in files:
            full_path = os.path.join(root, file)
            file_list.append(full_path)
    return file_list


def get_all_files_no_hidden(start_path):
    """返回指定目录及其子目录下的所有文件的完整路径列表。"""
    file_list = get_all_files(start_path)
    file_list = [file for file in file_list if not file.startswith(".")]
    return file_list


def replace_file(A_path: str, B_path: str):
    """
    删除指定的A文件，并将B文件重命名为A文件。

    参数:
        A_path (str): 原始A文件的路径
        B_path (str): 需要改名为A文件的B文件路径
    """
    # 检查并尝试删除A文件
    if os.path.exists(A_path):
        try:
            os.remove(A_path)
            print(f"已成功删除文件：{A_path}")
        except Exception as e:
            print(f"删除文件 {A_path} 时发生错误：{e}")
            return

    # 将B文件重命名为A文件
    try:
        os.rename(B_path, A_path)
        print(f"已成功将文件 {B_path} 重命名为 {A_path}")
    except Exception as e:
        print(f"重命名文件 {B_path} 至 {A_path} 时发生错误：{e}")


def read_file_content(file_path):
    """
    读取指定路径的文件内容，使用UTF-8编码

    参数:
        file_path (str): 文件路径

    返回:
        str: 文件内容
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
        return content
    except Exception as e:
        print(f"Error reading file {file_path}: {e}")
        return ""
